# -*- coding: utf-8 –*-
import time
import pickle

from mongoengine import StringField, IntField, BooleanField, \
    DateTimeField, ListField, PointField, ReferenceField, FloatField, \
    Document, EmbeddedDocument, URLField, EmbeddedDocumentField


class KV(Document):
    """
    key: value表，用来放配置
    """
    meta = {
        'collection': 'vacation_kv',
    }

    key = StringField(unique=True)
    value = StringField()
    expire = IntField(verbose_name=u'过期时间点')

    @staticmethod
    def get(key):
        result = KV.objects(key=key).first()
        if result:
            if result.expire != 0 and time.time() > result.expire:
                return
            return pickle.loads(result.value)
        return

    @staticmethod
    def set(key, value, timeout=0):
        """
        Note that get_or_create is now scheduled to be deprecated, because with no transaction support in MongoDB it cannot ensure atomicity.
        The preferred way is update with upsert:
        Location.objects(user_id=user_id).update_one(set__point=point, upsert=True)
        """
        value = pickle.dumps(value)
        expire = int(time.time()) + timeout if timeout else 0
        KV.objects(key=key).update_one(set__key=key, set__value=value, set__expire=expire, upsert=True)
